package org.elsfs.cloud.common.mybatis.injector.methods;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

/**
 * 根据查询条件判断记录是否存在
 *
 */
public class ExistsByWrapper extends AbstractMethod {

    /**
     * SQL脚本
     */
    private static final String SQL_SCRIPT = "<script>%s SELECT 1 FROM %s %s LIMIT 1 %s\n</script>";

    /**
     * @see AbstractMethod#AbstractMethod(String)
     * @since 3.5.0
     */
    public ExistsByWrapper() {
        super("existsByWrapper");
    }

    /**
     * 注入自定义 MappedStatement
     *
     * @param mapperClass mapper 接口
     * @param modelClass  mapper 泛型
     * @param tableInfo   数据库表反射信息
     * @return MappedStatement
     */
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        String sql = String.format(
            SQL_SCRIPT,
            this.sqlFirst(),
            tableInfo.getTableName(),
            this.sqlWhereEntityWrapper(true, tableInfo),
            this.sqlComment()
        );

        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
        return this.addSelectMappedStatementForOther(mapperClass, this.methodName, sqlSource, Boolean.class);
    }
}
